import {Command} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      const {current} = getData().main;
      let params = {
        giftType: current,
      };
      let result = await api.customerGiftController.giftinfoList(params);
      if (result.length > 0) {
        result.map((item, index) => {
          let list = [];
          if (item.couponIds && item.couponIds.length > 0) {
            let obj = {
              key: '优惠券',
              value: item.couponIds,
              type: 1,
            };
            list.push(obj);
          }
          if (item.goodsInfoIds && item.goodsInfoIds.length > 0) {
            let obj = {
              key: '甄选商品',
              value: item.goodsInfoIds,
              type: 2,
            };
            list.push(obj);
          }
          if (item.magicCoin != null && item.magicCoin > 0) {
            let obj = {
              key: '魔力币',
              value: item.magicCoin,
              type: 3,
            };
            list.push(obj);
          }
          if (item.points != null && item.points > 0) {
            let obj = {
              key: '积分',
              value: item.points,
              type: 4,
            };
            list.push(obj);
          }
          if (item.extraInfo && item.extraInfo.length > 0) {
            let arr = [];
            item.extraInfo.map((v) => {
              let obj = {type: 5, key: '', value: ''};
              obj.key = v;
              obj.value = v;
              arr.push(obj);
            });
            list = list.concat(arr);
          }
          item.list = list;
        });
        action.commonChange('main.giftList', result);
      }
    },
    async receive(giftId) {
      Taro.showLoading({
        title: '领取中',
      });
      let result = await api.customerGiftController.giftrecordinfoAdd({giftId});
      if (result.code == 'K-000000') {
        action.page();
        Taro.hideLoading();
        action.commonChange('main.successModel', true);
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageBreceivingGifts'),
  };
}

//create by moon https://github.com/creasy2010/moon
